package dws_tb

import (
	"fmt"
	"gorm.io/gorm"
	"server/global"
	"server/model/common/request"
)

type DwsTbService struct {
}


func (dwsTbService *DwsTbService) CreateDwsTb(dwsTb *DwsTb) (err error) {
	err = global.SysDB.Create(dwsTb).Error
	return err
}


func (dwsTbService *DwsTbService) DeleteDwsTb(dwsTb DwsTb) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&DwsTb{}).Where("id = ?", dwsTb.ID).Update("deleted_by", dwsTb.DeletedBy).Error; err != nil {
			return err
		}
		if err = tx.Delete(&dwsTb).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}


func (dwsTbService *DwsTbService) DeleteDwsTbByIds(ids request.IdsReq, delBy uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&DwsTb{}).Where("id in ?", ids.Ids).Update("deleted_by", delBy).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", ids.Ids).Delete(&DwsTb{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}


func (dwsTbService *DwsTbService) DeleteDwsTbByCol(colName string, colVal any, delBy uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		sqlDel := fmt.Sprintf("%s=?", colName)
		if err := tx.Model(&DwsTb{}).Where(sqlDel, colVal).Update("deleted_by", delBy).Error; err != nil {
			return err
		}
		if err := tx.Where(sqlDel, colVal).Delete(&DwsTb{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}


func (dwsTbService *DwsTbService) UpdateDwsTb(dwsTb DwsTb) (err error) {
	err = global.SysDB.Save(&dwsTb).Error
	return err
}


func (dwsTbService *DwsTbService) GetDwsTbById(id uint) (dwsTb DwsTb, err error) {
	err = global.SysDB.Where("id = ?", id).First(&dwsTb).Error
	return
}


func (dwsTbService *DwsTbService) GetDwsTbByCol(colName string, colVal any) (dwsTbs []DwsTb, err error) {
	sqlFind := fmt.Sprintf("%s=?", colName)
	err = global.SysDB.Where(sqlFind, colVal).Find(&dwsTbs).Error
	return
}


func (dwsTbService *DwsTbService) GetDwsTbInfoList(info DwsTbSearch) (list []DwsTb, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.SysDB.Model(&DwsTb{})
	var dwsTbs []DwsTb
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.SrcTbName != "" {
		db = db.Where("srcTbName = ?", info.SrcTbName)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&dwsTbs).Error
	return dwsTbs, total, err
}


func (dwsTbService *DwsTbService) GetAllDwsTbs() (dwsTb []DwsTb, err error) {
	err = global.SysDB.Find(&dwsTb).Error
	return dwsTb, err
}


func (dwsTbService *DwsTbService) GetDwsTb() (dwsTb []DwsTb, err error) {
	err = global.SysDB.Find(&dwsTb).Error
	return dwsTb, err
}
